/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.mobaas.devops.model.Application;
import com.mobaas.devops.model.Container;
import com.mobaas.devops.service.ApplicationService;
import com.mobaas.devops.service.BindingService;
import com.mobaas.devops.service.ContainerService;

/**
 * 
 * @author billy zhang
 * 
 */
@Service
public class BindingServiceImpl implements BindingService {

	@Autowired
    private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	private ApplicationService appService;
	
	@Autowired
	private ContainerService contService;
	
	@Override
	public List<String> getBackendList( String domain ) {
		
      	Set<Object> keys = stringRedisTemplate.boundHashOps(domain).keys();
      	List<String> list = new ArrayList<String>();
      	for (Object obj : keys) {
      		list.add((String)obj);
      	}
      	return list;
      
	}

	@Override
	public void register(Container container) {
		Application app = appService.selectApplicationById(container.getAppId());
		if (app != null) {
			String backend = container.getHostIp() + ":" + container.getHostPort();
			stringRedisTemplate.boundHashOps(app.getDomain()).put(backend, backend);
		}
	}

	@Override
	public void unregister(String containerId) {
		Container container = contService.selectContainerById(containerId);
		if (container == null)
			return;
		
		Application app = appService.selectApplicationById(container.getAppId());
		if (app == null)
			return;
		
		String backend = container.getHostIp() + ":" + container.getHostPort();
        stringRedisTemplate.boundHashOps(app.getDomain()).delete(backend);
		
	}
}
